package com.zzyl.intercept;

import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.utils.JwtUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //检查token是否为空
        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            //为空，返回信息，在拦截
            ResponseResult responseResult = ResponseResult.error("未登录");
            String jsonString = JSON.toJSONString(responseResult);
            response.getWriter().write(jsonString);
            System.out.println(1);
            return false;
        }
        //解析token,检查token是否正确
        try {
            JwtUtil.parseJWT("itheima",token);
        } catch (Exception e) {
            //解析失败，token不正确，返回信息，在拦截
            ResponseResult responseResult = ResponseResult.error("登录过期登录");
            String jsonString = JSON.toJSONString(responseResult);
            response.getWriter().write(jsonString);
            System.out.println(2);
            return false;
        }
        //token 正确，放行
        return true;
    }
}
